<template>
	<!--添加行程明细 -->
	<view style="background-color: #fff;margin-top: 20rpx;">
		<view>
			<uni-section title="基本信息" type="line"></uni-section>
		</view>
		<view style="height: 100%;padding-top: 20rpx;">
			<uni-forms ref="form" :modelValue="entity" label-width="100px">
				<!-- 行程名称 -->
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="行程名称:" name="ItineraryName">
						<uni-easyinput v-model="entity.ItineraryName" :inputBorder="false" :disabled="disabled" />
					</uni-forms-item>
				</view>
				<!-- 选择客户 -->
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="客户:" name="CustomerName">
						<view @click="CustomerChoice">
							<uni-easyinput v-model="entity.CustomerName" suffixIcon="compose" :disabled="disabled"
								:inputBorder="false" />
						</view>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="到达城市:" :rules="$rules.handle.ArrivalCityIdName" required
						name="ArrivalCityIdName">
						<uni-data-picker popup-title="请选择到达城市" :localdata="dataTree" :readonly="disabled"
							@change="pickerChange($event, 'ArrivalCityIdName')" :inputBorder="false"
							v-model="entity.ArrivalCityIdName">
						</uni-data-picker>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="到达日期:" :rules="$rules.handle.ArrivalDate" required name="ArrivalDate">
						<view @click="DateChange($event, 'ArrivalDate')">
							<uni-easyinput v-model="entity.ArrivalDate" :disabled="disabled" :inputBorder="false" />
						</view>
					</uni-forms-item>
				</view>
				<!-- 交通方式 -->
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="交通方式:" name="TransportationMode" :rules="$rules.handle.TransportationMode"
						required>
						<view>
							<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
								v-model="entity.TransportationMode" :localdata="ModeTransportationOptions"
								@change="selectOptionsChange($event, 'ModeTransportation')"
								:disabled="disabled"></uni-data-select>
						</view>
					</uni-forms-item>
				</view>
				<!-- 客户拜访说明 -->
				<view style="background-color: #fff;padding:0 20rpx;">
					<!-- :rules="$rules.handle.VisitRemark" required  -->
					<uni-forms-item label="客户拜访说明:" name="Infor">
						<view>
							<uni-easyinput v-model="entity.Infor" type="textarea" :adjust-position="false"
								:inputBorder="false" :disabled="disabled" />
						</view>
					</uni-forms-item>
				</view>
			</uni-forms>
			<view v-if="entity.CustomId && !disabled" class="flex Acentern"
				style="padding-right: 25rpx;padding-left: 20rpx;margin-bottom: 30rpx;margin-top: 15rpx;">
				<view class="flex Acentern" style="margin-right: 50rpx;" @click="CommunicationClick(1)">
					<u-icon name="plus-circle-fill" color="#2979ff" size="45"></u-icon>
					<text style="color:#2979ff;font-weight:bold;padding-left: 10rpx;">关联沟通记录</text>
				</view>
				<view class="flex Acentern" @click="CommunicationClick(2)">
					<u-icon name="plus-circle-fill" color="#2979ff" size="45"></u-icon>
					<text style="color:#2979ff;font-weight:bold;padding-left: 10rpx;">添加沟通记录</text>
				</view>
			</view>
			<!-- 关联的沟通记录列表 -->
			<view v-if="entity.salesmanDailyRecords" style="">
				<view v-if="entity.salesmanDailyRecords.length>0">
					<view style="font-size: 25rpx;padding-left: 20rpx;font-weight: bold;">已关联的沟通记录:</view>
					<block v-for="(item, index) in entity.salesmanDailyRecords" :key="index">
						<view style="display: flex;flex-wrap: wrap;padding-left: 20rpx;padding-right: 20rpx;">
							<u-tag @close="SalesmanDailyRecordstagCloseChange(item, index)"
								@click="SalesmanDailyRecordstagClickChange(item, index)"
								style="margin-right: 20rpx;margin-bottom: 15rpx;" :text="item.DailyRecordTitle"
								type="primary" :closeable="!disabled" />
						</view>

					</block>
				</view>
			</view>
		</view>
		<view v-if="!disabled" class="flex  Jbetween">
			<uni-section title="费用明细" type="line"></uni-section>
			<view class="flex Acenter Jbetween" @click="AddDetailClick" style="padding-right: 25rpx;">
				<u-icon name="plus-circle-fill" color="#2979ff" size="45"></u-icon>
				<text style="color:#2979ff;font-weight:bold;padding-left: 10rpx;">添加明细</text>
			</view>
		</view>

		<view class="scrollBox">
			<scroll-view style="width: 100%;height: 100%;" scroll-y="true">
				<view style="padding-bottom: 50px;padding-left: 20rpx;padding-right: 20rpx;">
					<!-- 报销费用明细 -->
					<view class="detail" v-for="(item, index) in detailData" :key="index">
						<view class="bold " style="font-size: 14px; color: #000;margin-bottom: 10rpx;">
							客户:<span class="font">{{item.CustomerName}}</span>
						</view>
						<view class="flex Jbetween" style="font-size: 14px">
							<span class="font">票据日期: {{ item.BillDate || "无" }}</span>
							<span class="font">业务性质:
								{{ item.newExpenseTypeName ? item.newExpenseTypeName :item.ExpenseType || "无" }}</span>
						</view>
						<view class="flex Jbetween" style="font-size: 14px">
							<span class="font">票据类型: {{ item.BillTypeName || "无" }}</span>
							<span class="font">发票分类: {{ item.InvoiceClassificationName || "无" }}</span>
						</view>
						<view class="flex Jbetween" style="font-size: 14px">
							<span class="font">票据张数: {{ item.BillsNum +' 张' || "无" }}</span>
							<span class="font">是否无票支出: {{ item.IsBill == true ? '是' : "否" }}</span>

						</view>
						<view class="flex Jbetween" style="font-size: 14px">
							<span class="font">票面金额: {{ item.FaceAmount || "无" }}</span>
							<span class="font">报销金额: {{ item.ReimburseAmount || "无" }}</span>
						</view>
						<view class="flex Jbetween" style="font-size: 14px">
							<span class="font">摘要: {{ item.ItemAbstract || "无" }}</span>
						</view>
						<view v-if="item.reimburse_Files" class="flex Jbetween" style="font-size: 14px">
							<span v-if="item.reimburse_Files.length>0" class="font">附件 *
								{{item.reimburse_Files.length}}</span>
							<span v-else class="font">附件 *0</span>
						</view>
						<view v-else class="flex Jbetween" style="font-size: 14px">
							<span class="font">附件 *0</span>
						</view>
						<view v-if="!disabled" class="flex Jend">
							<view @click.stop="handleItemEdit( entity, item, index)" style="
							  width: 15%;
							  border-radius: 5px;
							  line-height: 30px;
							  color: #fff;
							  text-align: center;
							  margin-top: 10rpx;
							  background-color: #2979ff;
							  margin-right: 30rpx;
							">
								修改
							</view>
							<view @click="detailDataDelete('delte',[item.Id], index)" style="
							  width: 15%;
							  border-radius: 5px;
							  line-height: 30px;
							  color: #fff;
							  text-align: center;
							  margin-top: 10rpx;
							 background-color: red;
							">
								删除
							</view>
						</view>
						<view v-else class="flex Jend">
							<view @click.stop="handleItemDetail( entity, item, index)" style="
							  width: 15%;
							  border-radius: 5px;
							  line-height: 30px;
							  color: #fff;
							  text-align: center;
							  margin-top: 10rpx;
							  background-color: #2979ff;
							">
								查看
							</view>
						</view>
					</view>
					<view v-if="detailData">
						<view style="margin: 50rpx 0;" v-if="detailData.length==0">
							<u-empty text="请添加费用明细" mode="list"></u-empty>
						</view>
					</view>
				</view>

			</scroll-view>
		</view>
		<block v-if="!disabled">
			<view class="submitButton">
				<u-button type="primary" @click="handleSubmitDetailSave">保存</u-button>
			</view>
		</block>


		<!-- 引用客户组件 -->
		<Myuser @customerChoice="Client" ref="myuser" @tagCloseChange="tagCloseChange" />

		<!-- 引用沟通关联组件 -->
		<CommunicationVue ref="CommunicationVue" @CommunicationConfirm="CommunicationConfirm" />
		<!-- 选择日期 -->
		<u-calendar v-model="isCalendar" :mode="mode" @change="calendarChange"></u-calendar>
	</view>
</template>

<script>
	// 沟通关联组件
	import CommunicationVue from "../../components/Communication.vue";
	//客户
	import Myuser from "../../components/Myuser.vue";
	import {
		mapState
	} from "vuex";
	// 引入公共接口文件
	import {
		// 差旅报销单 行程子表删除
		Reimburse_Travel_Business_ItemDeleteData,
		// 差旅报销单 行程子表下的费用明细子表删除
		Reimburse_Travel_Business_SubsidyDeleteData,
		// 取消沟通记录的关联
		SalesmanDailyRecordDisassociateData
	} from "@/api/interface.js";
	export default {
		components: {
			// 客户组件
			Myuser,
			// 沟通关联组件
			CommunicationVue
		},
		data() {
			return {
				entity: {},
				// 是否显示日期弹窗
				isCalendar: false,
				// 日期选择
				mode: 'date',
				// 禁用
				disabled: false,
				// 加载
				loading: false,
				// 点击的是开始日期还是结束日期
				DateType: "",
				// 地区树结构
				dataTree: [],
				// 费用明细列表
				detailData: [],
				// 交通方式下拉列表数据
				ModeTransportationOptions: [],
				// 做数据处理的选择的客户名称
				StrCustomerNameArr: [],
				// 做数据处理的选择的客户id
				StrCustomIdArr: [],

			}
		},
		computed: {
			...mapState(["UserInfo", "BillTypeOptions", "ExpenseTypeOptions", "InvoiceClassificationOptions",
				"CompayListOptions", "Base_DistrictGetTreeDataOptions", "TransportationModeOptions"
			]),
		},
		onLoad(options) {
			// 城市的确树结构
			this.dataTree = this.Base_DistrictGetTreeDataOptions
			// 交通方式下拉列表数据
			this.ModeTransportationOptions = this.TransportationModeOptions
			if (uni.getStorageSync('entity')) {
				let data = uni.getStorageSync('entity')
				console.log('获取存换entidatadataty', data)
				// 查看
				if (data.disabled) {
					this.disabled = data.disabled
					uni.setNavigationBarTitle({
						title: '行程详情'
					})
				}
				// 赋值行程主表
				this.entity = data.item
				console.log('行程子表编辑过来的-------------------------', data, this.entity, this.detailData)
				this.detailData = data.item.reimburse_Travel_Business_SubsidyDTOs ? data.item
					.reimburse_Travel_Business_SubsidyDTOs : data.item.detailData
				this.$forceUpdate()
			}
			uni.removeStorageSync('entity')

			// // 达到城市编辑回显
			// this.entity.ArrivalDate = data.item.ArrivalDate
			// // 达到城市编辑回显
			// this.entity.ArrivalCityIdName = data.item.ArrivalCityIdName
			// // 费用明细子表赋值
			// this.detailData = data.item.detailData
		},
		methods: {
			// 添加和关联沟通记录点击
			CommunicationClick(type) {
				console.log('添加还是关联', type, this.entity)
				if (type == 1) {
					// 点击的是关联沟通记录
					// 选择关联沟通记录列表
					this.$refs.CommunicationVue.openForm(this.entity.CustomerNameOptions, this.entity.salesmanDailyRecords)

				} else {
					// 点击的是添加沟通记录
					uni.navigateTo({
						url: "/pages/Cust_Communication/AddForm?title=新建沟通记录&CustomId=" + this.entity.CustomId +
							'&CustomerName=' + this.entity.CustomerName
					})
				}
			},
			// 已关联的沟通记录查看详情
			SalesmanDailyRecordstagClickChange(item, index) {
				console.log('点击查看闲情', item, index)
				uni.navigateTo({
					url: "/pages/Cust_Communication/EditForm?Id=" + item.Id + "&title=查看沟通记录"
				})
			},
			// 已关联的沟通列表标签关闭
			SalesmanDailyRecordstagCloseChange(item, index) {
				let obj = this.entity.salesmanDailyRecords[index]
				// 暂时不掉接口
				// 取消沟通记录的关联
				SalesmanDailyRecordDisassociateData(obj).then(resJson => {
					if (resJson.Success) {
						// 更新视图
						let arr = this.entity.salesmanDailyRecords.filter(item => item.Id !== obj.Id)
						console.log('删除沟通记录了', obj, arr)
						this.entity.salesmanDailyRecords = arr
						this.$sucessToast('已删除')
					}
				})
			},
			// 客户组件里的关联客户关闭标签
			tagCloseChange(index) {
				// 同步处理选中好的客户名称数组和id数组
				this.StrCustomerNameArr.splice(index, 1)
				this.StrCustomIdArr.splice(index, 1)
				console.log('关闭标签了', index, this.StrCustomIdArr, this.StrCustomerNameArr)
			},
			//本条客户的数据
			Client(arr) {
				console.log('选择客户确定好后传递父组件的值---------------', arr, this.entity)

				let CustomerNameArr = arr.map(item => {
					return item.cCusName
				})
				let CustomIdArr = arr.map(item => {
					return item.Id
				})
				let CustomerName = CustomerNameArr.join(',')
				let CustomId = CustomIdArr.join(',')

				if (!this.entity.CustomId) {
					console.log('走没有选择客户时候的', CustomerNameArr, CustomIdArr, CustomerName, CustomId)
					this.$set(this.entity, "CustomerName", CustomerName);
					this.entity.CustomId = CustomId
					// 直接插入选中的下拉客户数组  用于添加行程明细选择客户使用
					this.$set(this.entity, "CustomerNameOptions", arr);
				} else {

					let newCustomerNameArr = []
					let newCustomIdArr = []
					newCustomerNameArr = this.entity.CustomerName.split(',')
					newCustomIdArr = this.entity.CustomId.split(',')

					this.StrCustomerNameArr = arr.map(item => {
						return item.cCusName
					})
					this.StrCustomIdArr = arr.map(item => {
						return item.Id
					})
					console.log('走详情详情详情有选择客户时候的', newCustomerNameArr, newCustomIdArr, CustomerName, CustomId, arr)
					console.log('过滤的', this.StrCustomerNameArr, this.StrCustomIdArr)
					// 选中的客户名称数据格式化参数
					this.$set(this.entity, "CustomerName", this.StrCustomerNameArr.join(','));
					// // 选中的客户id 格式化参数
					this.$set(this.entity, "CustomId", this.StrCustomIdArr.join(','));
					// 	// 直接插入选中的下拉客户数组  用于添加行程明细选择客户使用
					this.$set(this.entity, "CustomerNameOptions", arr);
				}
				// 选择关联沟通记录列表
				this.$refs.CommunicationVue.openForm(arr)
			},
			//选择客户
			CustomerChoice(type) {
				if (this.disabled) return
				this.$refs.myuser.openForm(this.entity);
			},
			// 交通方式选择
			selectOptionsChange(event, key) {
				console.log('修改交通方式选择', event, key, this.entity, this.ModeTransportationOptions)
				// 处理交通方式名称用于渲染
				let ModeTransportationOptionsName = this.ModeTransportationOptions.filter(item => item.value ==
						event)[0]
					.text
				this.$set(this.entity, key + 'Name', ModeTransportationOptionsName)
				this.$set(this.entity, 'ModeTransportationOptions', this.ModeTransportationOptions[event])
			},
			// 添加明细
			AddDetailClick() {
				console.log('修改条件添加明细了', this.entity)
				let entity = JSON.stringify(this.entity)
				uni.setStorageSync('entity', entity)
				// 报销明细
				uni.navigateTo({
					url: "/pages/Approval/AddDetailReim"
				})
			},
			// 关联沟通记录子组件回调
			CommunicationConfirm(data) {
				// 过滤出选中的列表
				let arr = data.filter(item => item.checked == true)
				console.log('关联沟通记录子组件回调--', data, this.entity, arr)
				if (arr.length == 0) {
					// 判断返回的关联沟通记录结果过来的是否是空数组  默认格式化数据
					// 如果没有关联沟通记录  默认空数组
					if (data.length == 0) {
						// 插入参数传给后台记录
						this.entity['salesmanDailyRecords'] = this.entity.salesmanDailyRecords ? this.entity
							.salesmanDailyRecords : []
						return
					}
					// 说明灭有选择关联的沟通记录列表
					return
				}
				if (!this.entity.salesmanDailyRecords) {
					// 插入参数传给后台记录
					this.entity['salesmanDailyRecords'] = arr
				} else {
					this.entity.salesmanDailyRecords = this.entity.salesmanDailyRecords.concat(arr)
				}

				console.log('EditDetailTrip关联子组件回调回来的data', data, arr, this.entity)
				this.$forceUpdate()
			},
			// 出发城市和到达城市
			pickerChange(event, key) {
				let arr = event.detail.value
				// // 出发城市名称
				let ArrivalCityIdName = arr.map(item => {
					return item.text
				}).join('/')
				// // 出发城市id
				let ArrivalCityId = arr.map(item => {
					return item.value
				}).join('/')
				this.$set(this.entity, 'newArrivalCityId', ArrivalCityId)
				this.$set(this.entity, 'ArrivalCityId', ArrivalCityId)
				this.$set(this.entity, 'newArrivalCityIdName', ArrivalCityIdName)
				this.$set(this.entity, 'ArrivalCityIdName', arr)
				console.log('到达城市选择了', event, this.entity, )
			},
			// 选择日期确定
			calendarChange(event) {
				if (this.options.DepartureDate === 'undefined') {
					this.$errorToast('您没有选择出发日期')
					return
				}
				let DepartureDate = new Date(this.options.DepartureDate).getTime()
				// 当前选择的到达日期
				let ArrivalDate = new Date(event.result).getTime()
				if (ArrivalDate < DepartureDate) {
					this.$errorToast('到达日期不能小于出发日期')
					return
				}
				if (this.options.ReturnDate === 'undefined') {
					this.$errorToast('您没有选择返回日期')
					return
				}
				let ReturnDate = new Date(this.options.ReturnDate).getTime()
				if (ArrivalDate > ReturnDate) {
					this.$errorToast('到达日期不能大于返回日期')
					return
				}
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
				this.$set(this.entity, 'ArrivalDate', event.result);
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
			},
			// 出发日期和到达日期选择
			DateChange(event, key) {
				if (this.disabled) return
				this.isCalendar = true
			},
			// 行程下的费用子表删除
			detailDataDelete(type, rowId, index) {
				console.log('行程子表开始删除了------------', type, rowId, index)
				var that = this
				this.$utils.showConfirm({
					content: '确定要删除吗',
					confirmText: "删除",
					confirmColor: "#D1100b"
				}).then(res => {
					if (res.confirm) {
						// 视图删除
						if (rowId[0] == undefined) {
							// 视图删除
							that.detailData.splice(index, 1)
							that.$sucessToast('已删除')
							return
						}
						uni.showLoading({
							title: '删除中'
						})
						this.loading = true
						Reimburse_Travel_Business_SubsidyDeleteData(rowId).then(resJson => {
							if (resJson.Success) {
								// 视图删除
								that.detailData.splice(index, 1)
								that.$sucessToast('已删除')
								setTimeout(function() {
									that.loading = false
									uni.hideLoading()
								}, 2500)

							} else {
								that.$errorToast(resJson.Msg);
								setTimeout(function() {
									that.loading = false
									uni.hideLoading()
								}, 2500)
							}
						})
					} else {
						this.loading = false;
					}
				})
			},
			// 子表编辑
			handleItemEdit(entity, item, index) {

				console.log('修改费用明细子表了', entity, item, index)

				let data = {
					entity: entity,
					item: item
				}
				this.detailDataIndex = index
				uni.setStorageSync('entity', data)
				uni.navigateTo({
					url: "/pages/Approval/EditDetailReim"
				})

			},
			// 查看
			handleItemDetail(entity, item, index) {
				console.log('查看', entity, item, index)
				let data = {
					entity: entity,
					item: item,
					disabled: true
				}
				uni.setStorageSync('entity', data)
				this.detailDataIndex = index
				uni.navigateTo({
					url: "/pages/Approval/EditDetailReim"
				})

			},
			// push报销明细子表
			setDetailData(type, data) {
				if (type === 'add') {
					// 走新增逻辑
					console.log('这里是新增费用明细了---------', type, data)
					this.detailData.push(data)
				} else {

					let newDetailData = this.detailData
					newDetailData.forEach((item, index) => {
						if (item.Id && item.Id === data.Id) {
							newDetailData[index] = data
						} else {
							// 替换数组里对应对象
							this.detailData.splice(this.detailDataIndex, 1, data)
						}
					})
					this.$forceUpdate()
					// 走修改逻辑
					console.log('这里是编辑费用明细了---------', type, data, newDetailData)
				}
			},
			// 添加行程保存
			handleSubmitDetailSave() {
				var that = this
				this.$refs.form.validate().then(res => {
					let pages = getCurrentPages() // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
					let prevPage = pages[pages.length - 2] //上一页页面实例
					this.entity['detailData'] = this.detailData
					// 单独处理到达城市id参数
					this.entity.ArrivalCityId = this.entity.newArrivalCityId
					console.log('差旅报销修改修改修改行程行程行程可以保存了-------------', this.entity, this.detailData)
					uni.navigateBack({
						delta: 1,
						success: () => {
							prevPage.$vm.setDetailData('edit', '行程', this
								.entity) // 给上一页绑定方法otherFun,传参地址id
						}
					})

				}).catch(err => {})
			},
			init() {},
			openForm(data) {
				this.init()
			},
			close() {
				this.$emit('close')
			}
		}
	}
</script>

<style lang="less" scoped>
	/* 设置 label 的样式 */
	::v-deep.uni-forms-item {
		padding-right: 40rpx !important;

		/* 例如，设置 label 的宽度和对齐方式 */
		.uni-forms-item__label {
			display: flex !important;
			justify-content: flex-end !important;
		}
	}

	// 覆盖uniapp 的 uni-data-select 央视
	::v-deep.uni-select {
		border: none !important;
	}

	// 覆盖uni-data-pirker 样式
	::v-deep.input-value-border {
		border: none !important;
	}

	// 覆盖uviewform表单form-item的下边距
	::v-deep.uni-forms-item {
		margin-bottom: 0 !important;
		border-bottom: 1px solid #EEE;
		padding-top: 20rpx !important;
		padding-bottom: 20rpx !important;
	}

	.scrollBox {

		margin-bottom: 130rpx;
		/* #ifdef H5 */
		height: calc(100vh - 360px);
		/* #endif */
		/* #ifdef APP */
		height: calc(100vh - 220px);
		/* #endif */

		.detail {
			width: 100%;
			margin: 0 auto;
			box-shadow: 3px 4px 16px 0px #6b6b6a;
			margin-top: 40rpx;
			margin-bottom: 10px;
			background-color: #ffffff;
			border-radius: 10rpx;
			padding: 20rpx;
		}
	}

	.submitButton {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 100rpx;
		/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
		height: calc(130rpx + constant(safe-area-inset-bottom));
		/* 直接扩展高度，因为padding-bottom是内边距 */
		height: calc(130rpx + env(safe-area-inset-bottom));
		/* 直接扩展高度 */
		background: #fff;
		padding-top: 10rpx;
		box-sizing: border-box;
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 iOS<11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS>= 11.2*/
		border-top: 1px solid #e9e9e9;
		padding-left: 15px;
		padding-right: 15px;
	}
</style>